using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Audio;
using System.Threading;

namespace StupidSpaceThing
{
	internal static class SoundSystem
	{
		private static AudioEngine audioEngine;
		public static SoundBank SoundBank;
		private static WaveBank waveBank;

		public static Cue music;
		public static Cue motor;
		public static Cue shot;
		public static Cue explode;

		private static Thread thread;

		public static bool PlaySound = true;

		public static void Init() {
			audioEngine = new AudioEngine(@"Content\Sound\Beta.xgs");
			SoundBank = new SoundBank(audioEngine, @"Content\Sound\Sound Bank.xsb");
			waveBank = new WaveBank(audioEngine, @"Content\Sound\Wave Bank.xwb");


			motor = SoundBank.GetCue("motor_1");
			shot = SoundBank.GetCue("shot");
			explode = SoundBank.GetCue("explode");
			music = SoundBank.GetCue("music");

			thread = new Thread(new ThreadStart(update));
			thread.Start();
		}
		
		public static void PlayCue(string cue, AudioListener listener, AudioEmitter emitter) {
			if( PlaySound && SoundBank != null ) {
				try {
					SoundBank.PlayCue(cue, listener, emitter);
				} catch { }
			}
		}

		private static void update() {

			#if XBOX
			thread.SetProcessorAffinity(5);
			#endif

			while( true ) {

				if( audioEngine != null && PlaySound ) {
					audioEngine.Update();
					if( !music.IsPlaying ) {
						if( music.IsStopped || music.IsStopping ) {
							music = SoundBank.GetCue("music");
						}
						music.Play();
					}
					if( Game1.Player != null && !Game1.Player.Entity.Dead ) {
						if( !motor.IsPlaying ) {
							if( motor.IsStopped || motor.IsStopping ) {
								motor = SoundBank.GetCue("motor_1");
							}
							motor.Play();
						}
						motor.SetVariable("DopplerPitchScalar", (float)Math.Pow(Game1.Player.Entity.ColObject.LinearVelocity.Length(), 0.3));
					} else {
						motor.Stop(AudioStopOptions.Immediate);
					}
				}
				Thread.Sleep(30);
			}
		}

		public static void UnloadContent() {
			thread.Abort();
			audioEngine.Dispose();
			audioEngine = null;
			SoundBank.Dispose();
			SoundBank = null;
			waveBank.Dispose();
		}
	}
}
